<template>
  <div style="display: flex; flex-direction: column; gap: 20px; width: 600px; padding: 0;">
    <!-- 按钮组 -->
    <div style="display: flex; flex-direction: row; gap: 10px; margin-top: 10px;">
      <div class="btn btn-primary"
           style="background-color: #FB7299; border-color: #FB7299; max-height: 30px;width: 100px;"
           @click="handleClick('5_minute')"
      >
        每5分钟
      </div>
      <div class="btn btn-primary"
           style="background-color: #FB7299; border-color: #FB7299; max-height: 30px;width: 100px;"
           @click="handleClick('hour')"
      >
        每小时
      </div>
      <div class="btn btn-primary"
           style="background-color: #FB7299; border-color: #FB7299; max-height: 30px;width: 100px;"
           @click="handleClick('day')"
      >
        每天
      </div>
    </div>

    <!-- 图表容器：显式设置宽度和高度 -->
    <div ref="chartContainer" style="width: 100%; height: 400px;"></div>
  </div>
</template>

<script setup>
import {ref, watch, onMounted, onBeforeUnmount} from 'vue';
import * as echarts from 'echarts';

const emit = defineEmits(
    ['changeMode'],
)
const props = defineProps({
  // 图表宽度
  width: {
    type: String,
    default: '100%'
  },
  // 图表高度
  height: {
    type: String,
    default: '100%'
  },
  // x轴数据
  xAxisData: {
    type: Array,
    default: () => ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  },
  // 系列数据
  seriesData: {
    type: Array,
    default: () => [150, 230, 224, 218, 135, 147, 260]
  },
  // 图表标题
  title: {
    type: String,
    default: ''
  },
  // 图表主题
  theme: {
    type: String,
    default: null
  },
  // 渲染方式
  renderer: {
    type: String,
    default: 'canvas',
    validator: value => ['canvas', 'svg'].includes(value)
  },
  // 是否启用动画
  animation: {
    type: Boolean,
    default: true
  },
  // 是否启用响应式
  responsive: {
    type: Boolean,
    default: true
  }
});

const chartContainer = ref(null);
const chart = ref(null);

const initChart = () => {
  if (!chartContainer.value) return;

  chart.value = echarts.init(chartContainer.value, props.theme, {
    renderer: props.renderer
  });
  updateChart();
};

const handleClick = (type) =>{
  emit('changeMode',{type: type});
};

const updateChart = () => {
  if (!chart.value) return;

  // 计算数据的最大值和最小值
  const dataMin = Math.min(...props.seriesData);
  const dataMax = Math.max(...props.seriesData);
  const range = dataMax - dataMin;

  // 计算合适的取整步长
  const getNiceStep = (range) => {
    const exponent = Math.floor(Math.log10(range));
    const fraction = range / Math.pow(10, exponent);
    let step = Math.pow(10, exponent);

    if (fraction > 5) step = 5 * step;
    else if (fraction > 2) step = 2 * step;

    step = Math.max(step, 2);

    return step;
  };

  const step = getNiceStep(range / 5); // 将范围分成约5段

  // 取整处理Y轴范围
  const niceMin = Math.floor((dataMin - range * 0.1) / step) * step;
  const niceMax = Math.ceil((dataMax + range * 0.1) / step) * step;

  const option = {
    title: {
      text: props.title,
      left: 'center',
      textStyle: {
        color: '#FB7299', // 粉色标题
        fontSize: 18,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'item', // 改为item触发，鼠标悬停在节点上显示
      formatter: '<br/>时间: {b}<br/>粉丝数: {c}', // 显示x轴标签和数值
      position: function (pos, params, dom, rect, size) {
        // 提示框位置调整，避免超出画布
        const obj = {top: 60};
        obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 5;
        return obj;
      }
    },
    animation: props.animation,
    xAxis: {
      type: 'category',
      data: props.xAxisData
    },
    yAxis: {
      type: 'value',
      min: niceMin,
      max: niceMax,
      interval: step  // 设置刻度间隔
    },
    series: [
      {
        data: props.seriesData,
        type: 'line',
        markLine: {
          silent: true,
          data: [
            {type: 'average', name: '平均值'}
          ]
        },
        markPoint: {
          data: [
            {type: 'max', name: '最大值'},
            {type: 'min', name: '最小值'}
          ]
        },
        showSymbol: false, // 不显示普通数据点
        symbolSize: 8,    // 节点大小
        itemStyle: {
          color: '#00A2E8', // 节点颜色
          borderWidth: 2,
          borderColor: '#fff'
        },
        label: {
          show: true,
          position: 'top',
          color: '#FFFFFF',
          fontSize: 12,
          fontWeight: 'bold',
          formatter: '{c}',
          textBorderColor: '#00AEEC',
          textBorderWidth: 2,
          textShadowColor: 'rgba(0,0,0,0.3)',
          textShadowBlur: 2,
          textShadowOffsetX: 1,
          textShadowOffsetY: 1
        },
        lineStyle: { // 添加线条样式设置
          color: '#FB7299' // 确保线条也是粉色
        },
        emphasis: { // 鼠标悬停时的样式
          itemStyle: {
            color: '#EE6666',
            borderWidth: 2,
            borderColor: '#fff',
            shadowBlur: 10,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
      }
    ],
    dataZoom: [
      {
        type: 'inside',
        start: 0,
        end: 100
      },
      {
        start: 0,
        end: 100
      }
    ]
  };

  chart.value.setOption(option);
};

const reinitChart = () => {
  if (chart.value) {
    chart.value.dispose();
  }
  initChart();
};

const handleResize = () => {
  if (chart.value) {
    chart.value.resize();
  }
};

onMounted(() => {
  initChart();
  if (props.responsive) {
    window.addEventListener('resize', handleResize);
  }
});

onBeforeUnmount(() => {
  if (chart.value) {
    chart.value.dispose();
  }
  if (props.responsive) {
    window.removeEventListener('resize', handleResize);
  }
});

watch(
    () => props.xAxisData,
    () => updateChart(),
    {deep: true}
);

watch(
    () => props.seriesData,
    () => updateChart(),
    {deep: true}
);

watch(
    () => props.theme,
    () => reinitChart()
);
</script>

<style scoped>
/* 可以添加一些样式 */

</style>